package com.migo.api;

import com.migo.annotation.IgnoreAuth;
import com.migo.entity.ShOrderInfoEntity;
import com.migo.entity.ShPhoneInfoEntity;
import com.migo.mongo.entity.AfterSaleMongo;
import com.migo.mongo.service.AfterSaleMongoService;
import com.migo.oss.OSSFactory;
import com.migo.service.ShOrderInfoService;
import com.migo.service.ShOrderStatusLineService;
import com.migo.service.ShPhoneInfoService;
import com.migo.service.SysOssService;
import com.migo.thread.AfterSaleThread;
import com.migo.thread.AfterSaleUserAddressThread;
import com.migo.thread.AfterSaleUserReceivingThread;
import com.migo.utils.*;
import com.migo.view.ShOrderInfoView;
import org.apache.commons.collections.map.LinkedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;

/**
 * Created by Wes on 2018/12/5.
 */
@CrossOrigin
@RestController
@RequestMapping("/api")
public class ApiAfterSaleController {
    private final Logger logger = LoggerFactory.getLogger(ApiAfterSaleController.class);

    @Autowired
    OSSFactory ossFactory;

    @Autowired
    private SysOssService sysOssService;

    @Autowired
    private ShOrderInfoService shOrderInfoService;

    @Autowired
    private ShOrderStatusLineService shOrderStatusLineService;

    @Autowired
    private AfterSaleMongoService afterSaleMongoService;

    @Value("${robot_mobile}")
    String robot_mobile;

    @Value("${back_url}")
    String back_url;


    @Value("${successful}")
    String successful;

    @Value("${fail}")
    String fail;


    @Value("${wechat_app}")
    String wechat_app;


    //vision+2 支付的配置--当前代码只在供应商服务114.215.28.4  生效
    @Value("${successRedirect}")
    String successRedirect;

    @Value("${failRedirect}")
    String failRedirect;

    @Value("${alipayRedirect}")
    String alipayRedirect;

    @Value("${wechatpayRedirect}")
    String wechatpayRedirect;

    @Value("${asback_url}")
    String asback_url;

    @Autowired
    private ShPhoneInfoService shPhoneInfoService;


    /**
     * 创建售后订单
     */
    @IgnoreAuth
    @RequestMapping("/createAfterSaleOrder")
    public R createAfterSaleOrder(@RequestBody String params) throws Exception {
        logger.error("上送params参数：" + params);
        ExecutorService threadPool = ThreadPoolUtils.getThreadPool();
        Map<String, String> mapFromJson = JsonUtils.getMapFromJson(params);
        System.out.println("mapFromJson:" + "----------------------------------------" + mapFromJson);
        System.out.println("-----------------------------------------------");
        String userId = mapFromJson.get("userId");
        System.out.println("userId:   " + userId);
        System.out.println("-----------------------------------------------");
        threadPool.execute(new AfterSaleThread(params, shOrderInfoService, ossFactory));
        return R.ok();
    }

    /**
     * 更新售后订单的用户物流信息，并更新订单状态
     *
     * @RequestParam Map<String, Object> params
     */
    @IgnoreAuth
    @RequestMapping("/updateUserAddressOfOrder")
    public R updateUserAddressOfOrder(@RequestBody String params) throws Exception {

        ExecutorService threadPool = ThreadPoolUtils.getThreadPool();
        threadPool.execute(new AfterSaleUserAddressThread(params, shOrderInfoService, shOrderStatusLineService, afterSaleMongoService));
        return R.ok();
    }


    /**
     * 更新售后订单的用户确定收货，并更新订单状态
     *
     * @RequestParam Map<String, Object> params
     */
    @IgnoreAuth
    @RequestMapping("/updateCustomerReceiving")
    public R updateCustomerReceiving(@RequestBody String params) throws Exception {
        System.out.println("**********************************************************");
        System.out.println("params:  "+params);
        System.out.println("**********************************************************");
        ExecutorService threadPool = ThreadPoolUtils.getThreadPool();
        threadPool.execute(new AfterSaleUserReceivingThread(params, shOrderInfoService, shOrderStatusLineService, afterSaleMongoService));
        return R.ok();
    }


    /**
     * 查询售后订单的日志
     */
    @IgnoreAuth
    @RequestMapping("/queryAfterSaleLog")
    public R queryAfterSaleLog(@RequestBody String params) throws Exception {
        Map<String, String> paramMap = JsonUtils.getMapFromJson(params);
        String orderId = paramMap.get("orderId");
        System.out.println("-------------------------------------");
        System.out.println("orderId   " + orderId);
        System.out.println("-------------------------------------");
        return R.ok().put("data", afterSaleMongoService.queryList(orderId));
    }

    /**
     * 获取售后订单列表
     */
    @IgnoreAuth
    @RequestMapping("/getAfterSaleOrderList")
    public R getAfterSaleOrderList(@RequestBody String params) throws Exception {
        List<ShOrderInfoEntity> shOrderList = new ArrayList<>();
        Map<String, String> paramMap = JsonUtils.getMapFromJson(params);
        if (paramMap.containsKey("userId")) {
            shOrderList = shOrderInfoService.queryUserOrderList(paramMap);
        }
        return R.ok().put("shOrderList", shOrderList);
    }


    /**
     * 取消售后订单
     */
    @IgnoreAuth
    @RequestMapping("/cancelAfterSaleOrder")
    public R cancelAfterSaleOrder(String orderId) throws Exception {
        if (orderId == null) {
            return R.error(6, "参数为null");
        }
        System.out.println(orderId);
        ShOrderInfoEntity shOrderInfoEntity = shOrderInfoService.queryObject(Integer.parseInt(orderId));
        System.out.println(shOrderInfoEntity.toString());
        shOrderInfoEntity.setOrderStatusId(99);
        shOrderInfoService.update(shOrderInfoEntity);
        return R.ok();
    }


    /**
     * 获取售后订单详情
     */
    @IgnoreAuth
    @RequestMapping("/getAfterSaleOrderDetail")
    public R getAfterSaleOrderDetail(@RequestBody String params) throws Exception {
        System.out.println("params" + "-------------------------------" + params);
        Map<String, String> paramMap = JsonUtils.getMapFromJson(params);
        System.out.println("paramMap" + "-------------------------------" + paramMap);
        Integer id = Integer.parseInt(paramMap.get("id"));
        System.out.println("id" + "-------------------------------" + id);
        ShOrderInfoView orderInfoView = shOrderInfoService.queryObjectById(id);
        return R.ok().put("orderDetail", orderInfoView);
    }


    /**
     * 获取售后订单详情
     */
    @IgnoreAuth
    @RequestMapping("/addLogistics")
    public R addLogistics(@RequestBody String params) throws Exception {
        Map<String, String> paramMap = JsonUtils.getMapFromJson(params);
        String logisticsName = paramMap.get("logisticsName");
        String logisticsCode = paramMap.get("logisticsCode");
        Integer id = Integer.parseInt(paramMap.get("id"));
        ShOrderInfoEntity shOrderInfo = shOrderInfoService.queryObject(id);
        shOrderInfo.setOrderLogisticsCode(logisticsName + "|" + logisticsCode);
        shOrderInfo.setOrderStatusId(3);
        shOrderInfoService.update(shOrderInfo);
        return R.ok();
    }


    /**
     * 微信支付同步回调函数
     */
    @IgnoreAuth
    @RequestMapping("/wechatReturnOrderInfo")
    public String wechatReturnOrderInfo(HttpServletRequest request) throws Exception {
        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            System.out.println(paramName + "=");
            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length == 1) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    System.out.println(paramValue);
                }
            }
        }
        return null;
    }


    /**
     * 更改售后订单状态
     */
    @IgnoreAuth
    @RequestMapping("/updateAfterSaleStatus")
    public boolean updateAfterSaleStatus(HttpServletRequest request) throws Exception {
        String orderId = request.getParameter("out_trade_no");
        String result_code = request.getParameter("result_code");
        String return_code = request.getParameter("return_code");
        String transaction_id = request.getParameter("transaction_id");
        System.out.println("result_code.equals:" + result_code.equals("SUCCESS"));
        System.out.println("return_code.equals:" + return_code.equals("SUCCESS"));

        if (result_code.equals("SUCCESS") && return_code.equals("SUCCESS")) {
            System.out.println("result_code---return_code:" + orderId);
            if (orderId.indexOf("_") > 0) {
                orderId = orderId.split("_")[0];
            }
            ShOrderInfoEntity shOrderInfo = shOrderInfoService.queryOrderId(orderId);
            Integer orderStatusId = shOrderInfo.getOrderStatusId();
            if (orderStatusId == 8) {

            } else {
                //后续需要添加状态更新记录--添加操作日志
                afterSaleMongoService.saveAfterLog(shOrderInfo, "微信支付成功！");
                if (shOrderInfo != null) {
                    shOrderInfo.setOrderStatusId(8);
                    shOrderInfo.setOrderPlayTime(DateUtil.getNow());
                    shOrderInfoService.update(shOrderInfo);
                    return true;
                } else {
                    //支付失败之后获取订单信息，发邮件通知公司相关责任人，进行处理
                }
            }
        }
        System.out.print("updateAfterSaleStatus_orderId" + orderId);
        return false;
    }


    /**
     * 检查支付宝售后订单状态
     */
    @IgnoreAuth
    @RequestMapping("/getOrderStatus")
    public String getOrderStatus(HttpServletRequest request) throws Exception {
        try {
            Map<String, Object> m = JsonUtils.getMapFromJson(request.getParameter("params"));
            String orderId = m.get("productid").toString();
            System.out.println("--------------------------------getOrderStatus:" + orderId);
            ShOrderInfoEntity shOrderInfo = shOrderInfoService.queryOrderId(orderId);
            return shOrderInfo.getOrderStatusId() + "";
        } catch (Exception e) {
            return -1 + "";
        }
    }


    /**
     * 支付宝更改订单状态
     */
    @IgnoreAuth
    @RequestMapping("/updateOrderAliPay")
    public String updateOrderAliPay(String params, HttpServletRequest request) throws Exception {
        try {
            System.out.println("params: " + params);
            Map<String, Object> m = JsonUtils.getMapFromJson(request.getParameter("params"));
            String orderId = m.get("productid").toString();
            System.out.println("--------------------------------updateOrderAliPay:" + orderId);
            ShOrderInfoEntity shOrderInfo = shOrderInfoService.queryOrderId(orderId);
            Integer orderStatusId = shOrderInfo.getOrderStatusId();
            if (orderStatusId == 8) {

            } else {
                shOrderInfo.setOrderStatusId(8);
                shOrderInfoService.update(shOrderInfo);
                //后续需要添加状态更新记录--添加操作日志
                List<AfterSaleMongo> afterSaleMongos = afterSaleMongoService.queryList(shOrderInfo.getOrderId());
                afterSaleMongoService.saveAfterLog(shOrderInfo, "支付宝支付成功！");
            }
            return 1 + "";
        } catch (Exception e) {
            return -1 + "";
        }
    }

    /**
     * 检查支付宝售后订单状态
     */
    @IgnoreAuth
    @RequestMapping("/chickAliPay")
    public ModelAndView chickAliPay(HttpServletRequest request) throws Exception {
        Map<String, Object> m = JsonUtils.getMapFromJson(request.getParameter("params"));
        String orderId = m.get("productid").toString();
        ModelAndView mv = new ModelAndView("redirect:" + fail + "");//redirect模式;
        System.out.println("--------------------------------chickAliPay:" + orderId);
        ShOrderInfoEntity shOrderInfo = shOrderInfoService.queryOrderId(orderId);
        if (shOrderInfo != null) {
            Integer statusId = shOrderInfo.getOrderStatusId();
            if (statusId == 8) {
                mv = new ModelAndView("redirect:" + successful + "");//redirect模式
            }
        }
        return mv;
    }

    /**
     * 检查微信支付售后订单状态
     */
    @IgnoreAuth
    @RequestMapping("/chickWechatPay")
    public ModelAndView chickWechatPay(HttpServletRequest request) throws Exception {
        String orderId = request.getParameter("orderId");
        ModelAndView mv = new ModelAndView("redirect:" + fail + "");//redirect模式;
        System.out.println("result_code---return_code:" + orderId);
        if (orderId.indexOf("_") > 0) {
            orderId = orderId.split("_")[0];
        }
        ShOrderInfoEntity shOrderInfo = shOrderInfoService.queryOrderId(orderId);
        if (shOrderInfo != null) {
            Integer statusId = shOrderInfo.getOrderStatusId();
            if (statusId == 8) {
                mv = new ModelAndView("redirect:" + successful + "");//redirect模式
            }
        }
        return mv;
    }


    /**
     * 获取售后订单详情(PVMG10支付)
     */
    @IgnoreAuth
    @RequestMapping("/afterSalePay")
    public ModelAndView afterSalePay(String orderId, Integer payWay, ModelMap m) throws Exception {
        System.out.println("orderId：" + orderId);
        System.out.println("payWay：" + payWay);
        ShOrderInfoEntity orderInfoView = shOrderInfoService.queryObject(Integer.parseInt(orderId));
        Map<String, Object> linkMap = new LinkedMap();
        ModelAndView mv;//redirect模式
        if (payWay == 0) {
            System.out.println("orderId：" + orderId);
            System.out.println("payWay：" + payWay);
            afterSaleMongoService.saveAfterLog(orderInfoView, "订单发起支付宝支付！");
            m.addAttribute("productid", orderInfoView.getOrderId());
            m.addAttribute("goods_tag", "PowerVision");
            m.addAttribute("total_fee", orderInfoView.getOrderPrice());
            m.addAttribute("product_description", "PowerVision");
            m.addAttribute("back_url", back_url + "?userId=" + orderInfoView.getUserId() + "&language=zh");
            System.out.println("支付宝支付" + JsonUtils.getJSONString(m));
            mv = new ModelAndView("redirect:" + robot_mobile + "");//redirect模式
        } else {
            System.out.println("orderId：" + orderId);
            System.out.println("payWay：" + payWay);
            afterSaleMongoService.saveAfterLog(orderInfoView, "订单发起微信支付！");
            m.addAttribute("price", orderInfoView.getOrderPrice());
            m.addAttribute("productid", orderInfoView.getOrderId() + "_" + GenCodeUtil.genCode());
            m.addAttribute("body", "PowerVision");
            m.addAttribute("goods_tag", "PowerVision");
            System.out.println("微信支付" + JsonUtils.getJSONString(m));
            mv = new ModelAndView("redirect:" + wechat_app + "");//redirect模式
        }
        return mv;
    }


    /**
     * 新版售后订单支付功能
     * 夏民版服务模块
     */
    @IgnoreAuth
    @RequestMapping("/asPay")
    public ModelAndView asPay(String orderId, Integer payWay, ModelMap m) throws Exception {
        ShOrderInfoEntity orderInfoView = shOrderInfoService.queryObject(Integer.parseInt(orderId));
        Map<String, Object> linkMap = new LinkedMap();
        ModelAndView mv;//redirect模式
        if (payWay == 0) {
            //后续需要添加状态更新记录--添加操作日志
            afterSaleMongoService.saveAfterLog(orderInfoView, "订单发起支付宝支付！");
            m.addAttribute("productid", orderInfoView.getOrderId());
            m.addAttribute("goods_tag", "PowerVision");
            m.addAttribute("total_fee", orderInfoView.getOrderPrice());
            m.addAttribute("product_description", "PowerVision");
            m.addAttribute("back_url", asback_url);
            System.out.println("支付宝支付" + JsonUtils.getJSONString(m));
            mv = new ModelAndView("redirect:" + alipayRedirect + "");//redirect模式
        } else {
            afterSaleMongoService.saveAfterLog(orderInfoView, "订单发起微信支付！");
            m.addAttribute("price", orderInfoView.getOrderPrice());
            m.addAttribute("productid", orderInfoView.getOrderId() + "_" + GenCodeUtil.genCode());
            m.addAttribute("body", "PowerVision");
            m.addAttribute("goods_tag", "PowerVision");
            System.out.println("微信支付" + JsonUtils.getJSONString(m));
            mv = new ModelAndView("redirect:" + wechatpayRedirect + "");//redirect模式
        }
        return mv;
    }

    /**
     * 获取售后电话
     *
     * @param language
     * @return
     */
    @IgnoreAuth
    @RequestMapping("/getPhone")
    public R getPhone(String language, Integer statusId) {
        ShPhoneInfoEntity shPhoneInfo = new ShPhoneInfoEntity();
        shPhoneInfo.setLanguage(language);
        shPhoneInfo.setStatusId(statusId);
        return R.ok().put("data", shPhoneInfoService.getPhone(shPhoneInfo));
    }
}
